<?php

namespace app\admin\model;

use think\Model;

class DateRestriction extends Model
{
    // 表名
    protected $name = 'date_restriction';
    
    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    
    // 追加属性
    protected $append = [
        'restriction_type_text',
        'status_text'
    ];
    
    /**
     * 限制类型列表
     */
    public static function getRestrictionTypeList()
    {
        return [
            'workdays' => '仅工作日',
            'weekends' => '仅周末', 
            'custom' => '自定义工作日',
            'specific' => '指定日期',
            'disabled' => '禁用日期'
        ];
    }
    
    /**
     * 状态列表
     */
    public static function getStatusList()
    {
        return [
            '0' => '禁用',
            '1' => '正常'
        ];
    }
    
    /**
     * 获取限制类型文本
     */
    public function getRestrictionTypeTextAttr($value, $data)
    {
        $list = self::getRestrictionTypeList();
        return isset($list[$data['restriction_type']]) ? $list[$data['restriction_type']] : '';
    }
    
    /**
     * 获取状态文本
     */
    public function getStatusTextAttr($value, $data)
    {
        $list = self::getStatusList();
        return isset($list[$data['status']]) ? $list[$data['status']] : '';
    }
    
    /**
     * 设置配置数据
     */
    public function setConfigDataAttr($value)
    {
        return is_array($value) ? json_encode($value, JSON_UNESCAPED_UNICODE) : $value;
    }
    
    /**
     * 获取配置数据
     */
    public function getConfigDataAttr($value)
    {
        return $value ? json_decode($value, true) : [];
    }
    
    /**
     * 根据配置键获取配置
     */
    public static function getConfigByKey($key)
    {
        $config = self::where('config_key', $key)
                     ->where('status', 1)
                     ->find();
        
        return $config ? $config->config_data : null;
    }
    
    /**
     * 验证日期是否符合限制
     */
    public static function validateDate($date, $configKey)
    {
        $config = self::getConfigByKey($configKey);
        if (!$config) {
            return ['valid' => true, 'message' => '无限制配置'];
        }
        
        $dateObj = new \DateTime($date);
        $dayOfWeek = $dateObj->format('w'); // 0=周日, 1=周一, ..., 6=周六
        
        switch ($config['restriction_type']) {
            case 'workdays':
                $isValid = ($dayOfWeek >= 1 && $dayOfWeek <= 5);
                $message = $isValid ? '日期有效' : '只能选择工作日（周一至周五）';
                break;
                
            case 'weekends':
                $isValid = ($dayOfWeek == 0 || $dayOfWeek == 6);
                $message = $isValid ? '日期有效' : '只能选择周末（周六、周日）';
                break;
                
            case 'custom':
                $allowedWeekdays = isset($config['allowed_weekdays']) ? $config['allowed_weekdays'] : [];
                $isValid = in_array($dayOfWeek, $allowedWeekdays);
                $message = $isValid ? '日期有效' : '该日期不在允许的星期范围内';
                break;
                
            case 'specific':
                $allowedDates = isset($config['allowed_dates']) ? $config['allowed_dates'] : [];
                $isValid = in_array($date, $allowedDates);
                $message = $isValid ? '日期有效' : '该日期不在允许的日期列表中';
                break;
                
            case 'disabled':
                $disabledDates = isset($config['disabled_dates']) ? $config['disabled_dates'] : [];
                $isValid = !in_array($date, $disabledDates);
                $message = $isValid ? '日期有效' : '该日期已被禁用';
                break;
                
            default:
                $isValid = true;
                $message = '日期有效';
        }
        
        return [
            'valid' => $isValid,
            'message' => $message,
            'date' => $date
        ];
    }
    
    /**
     * 生成禁用日期列表
     */
    public static function generateDisabledDates($config, $startDate = null, $endDate = null)
    {
        if (!$startDate) {
            $startDate = date('Y-m-d', strtotime('-1 year'));
        }
        if (!$endDate) {
            $endDate = date('Y-m-d', strtotime('+2 years'));
        }
        
        $disabledDates = [];
        $currentDate = new \DateTime($startDate);
        $endDateObj = new \DateTime($endDate);
        
        while ($currentDate <= $endDateObj) {
            $dateString = $currentDate->format('Y-m-d');
            $dayOfWeek = $currentDate->format('w');
            $shouldDisable = false;
            
            switch ($config['restriction_type']) {
                case 'workdays':
                    $shouldDisable = ($dayOfWeek == 0 || $dayOfWeek == 6);
                    break;
                    
                case 'weekends':
                    $shouldDisable = ($dayOfWeek >= 1 && $dayOfWeek <= 5);
                    break;
                    
                case 'custom':
                    $allowedWeekdays = isset($config['allowed_weekdays']) ? $config['allowed_weekdays'] : [];
                    $shouldDisable = !in_array($dayOfWeek, $allowedWeekdays);
                    break;
                    
                case 'specific':
                    $allowedDates = isset($config['allowed_dates']) ? $config['allowed_dates'] : [];
                    $shouldDisable = !in_array($dateString, $allowedDates);
                    break;
                    
                case 'disabled':
                    $disabledDates = isset($config['disabled_dates']) ? $config['disabled_dates'] : [];
                    $shouldDisable = in_array($dateString, $disabledDates);
                    break;
            }
            
            if ($shouldDisable) {
                $disabledDates[] = $dateString;
            }
            
            $currentDate->add(new \DateInterval('P1D'));
        }
        
        return $disabledDates;
    }
}